import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:dio/dio.dart';
import 'dart:convert';
import '../../routes/application.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:provide/provide.dart';
import '../../provide/setting.dart';

class SearchResult extends StatefulWidget {
  final String keyword;

  SearchResult({Key key, this.keyword}) : super(key: key);

  _SearchResultState createState() => _SearchResultState();
}

class _SearchResultState extends State<SearchResult> {

  TextEditingController _textEditingController = new TextEditingController();
  List results = [];
  Future _future;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _textEditingController.text = widget.keyword;
    _future = _getResult(_textEditingController.text);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomPadding: false,
      appBar: AppBar(
        title: Container(
          width: ScreenUtil().setWidth(500),
          height: ScreenUtil().setHeight(80),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(50),
          ),
          child: TextField(
            controller: _textEditingController,
            textInputAction: TextInputAction.search,
            decoration: InputDecoration(
              contentPadding: EdgeInsets.all(10),
              border: InputBorder.none,
              fillColor: Colors.black12,
              filled: true,
              hintText: '请输入关键词',
              suffixIcon: IconButton(
                icon: Icon(Icons.clear),
                onPressed: (){
                  _textEditingController.clear();
                },
              )
            ),
            onSubmitted: (str){
              _getResult(str);
            },
          ),
        )
      ),
      body: _wrapList()
    );
  }

  // 获取搜索结果
  Future _getResult(word) async {
    if(word==''){
      Fluttertoast.showToast(
        msg: '请输入搜索词！',
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        timeInSecForIos: 2,
        backgroundColor: Theme.of(context).primaryColor,
        textColor: Colors.white,
        fontSize: 16.0
      );
      return 'not';
    }
    Dio dio = new Dio();
    var formData = {
      'keyWord': word
    };
    Response response = await dio.post('http://dianshan.free.idcfengye.com/goods/getGoodsInfoByKeyWord',data: formData);
    print(response);
    var data = json.decode(response.toString());
    results = data['message'];
    // 提交搜索词 更新次数
    formData = {
      'keyword':word
    };
    dio.post('http://dianshan.free.idcfengye.com/goods/postkeyword',data: formData);
    setState(() {// 刷新页面显示中的数据
      
    });
    return response.toString();
  }

  // 搜索结果
  Widget _wrapList(){
    return FutureBuilder(
      future: _future,
      builder: (context,snapshot){
        if(snapshot.hasData){
          if(results.isEmpty){
            return Center(
              child: Text('搜索无结果'),
            );
          }
          List<Widget> listWidget = results.map((item){
            return InkWell(
              onTap: (){
                Application.router.navigateTo(context,"/detail?id=${item['ID']}");
              },
              child: Container(
                width: ScreenUtil().setWidth(372),
                color: Colors.white,
                padding: EdgeInsets.all(5),
                margin: EdgeInsets.only(bottom: 3),
                child: Column(
                  children: <Widget>[
                    Container(
                      width: ScreenUtil().setWidth(375),
                      child: Provide<SettingProvide>(
                        builder: (context,child,val){
                          return val.noImage?Image.asset('images/noImage.png')
                                            :CachedNetworkImage(
                                              imageUrl: item['IMAGE1'],
                                              placeholder: (context, url) => Center(
                                                child: Text('正在加载',style: TextStyle(color: Colors.white),),
                                              ),
                                              errorWidget: (context, url, error){
                                                return Container(
                                                  height: ScreenUtil().setHeight(350),
                                                  child: new Icon(Icons.error),
                                                );
                                              },
                                              fit: BoxFit.contain,
                                            );
                      },
                    ),
                    ),
                    Text(
                      item['NAME'],
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(color: Theme.of(context).primaryColor,fontSize: ScreenUtil().setSp(26)),
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Text('￥${item['PRESENT_PRICE']}'),
                        Text(
                        '￥${item['ORI_PRICE']}',
                        style: TextStyle(color: Colors.black26,decoration: TextDecoration.lineThrough), 
                        )
                      ],
                    )
                  ],
                ),
              ),
            );
          }).toList();
          return SingleChildScrollView(
              child: Wrap(
              spacing: 2,
              children: listWidget
            ),
          );
        }else {
          return Center(
            child: Text('加载数据中'),
          );
        }
      },
    );
  }
}
